
// $(document).foundation();
// Meteor.autosubscribe() {
// 	Meteor.subscribe("topics",Session.get('page'));
// }
Session.setDefault('page', 1);
Deps.autorun(function() {
	Meteor.subscribe("topics",Session.get('page'),Session.get('category'));
	Meteor.subscribe("replys",Session.get('topic_id'));
});
Meteor.subscribe("users");
Meteor.subscribe("all_category");
function formData (form) {
	var data = {};
	$.each($(form).serializeArray(), function(i, field) {
		data[field.name] = field.value;
		// console.log (field);
	});
	return data;
}
Session.setDefault("errMsg", "有一个错误存在");
function showErr (msg, errtitle) {
	var errtitle = errtitle || "Error";
	Session.set('errbox', true);
	Session.set("errMsg", msg);
	Session.set("errtitle", errtitle);
}
function getUsername (userid) {
	var user = Meteor.users.findOne({_id: userid});
	return (user.profile && user.profile.name) ? user.profile.name : user.username;
}
// function isAdminById (userId) {
// 	return Meteor.users.find({_id: userId, isAdmin:true});
// }
function adminUsers () {
	return Meteor.users.find({isAdmin: true}).fetch();
}
function isAdminById (userId) {
	var user = Meteor.users.findOne(userId);
	if(!user || typeof user === 'undefined');
		return false;
	return user.isAdmin;
}
var view_helps = {
	user :  function () {
		// var uid = userid ? userid : this.userId;
		return getUsername(this.userId);
		// var user = Meteor.users.findOne({_id: this.userId});
		// return (user.profile && user.profile.name) ? user.profile.name : user.username;
	},
	'fromnow': function (t) {
		return moment.utc(t).fromNow();
	}

};
/*Template.nav.events({
	'click .tohome': function () {
		Meteor.Router.to('/');
	},
	'click .topost': function () {
		Meteor.Router.to('/p');
	},
	'click .button': function () {
		Meteor.Router.to('/p');
	}
});*/
// Template.post.helpers({
// 	'errbox': function () {
// 		return Session.get('errbox');
// 	},
// 	'errMsg': function () {
// 		return Session.get('errMsg');
// 	}
// });
// Template.notice.helpers({
// 	'notices': function () {
// 		return notices.find({userId: Meteor.userId}, {sort:{timestamp: -1}});
// 	},
// 	'notices_count': function () {
// 		var notices = Notices.find({userId: Meteor.userId(), read: false}).fetch();
// 	}
// })
Template.topics.helpers(view_helps);
Template.topic.helpers(view_helps);
Template.replys.helpers(view_helps);
Template.member.helpers(view_helps);
Template.topics.helpers({
	'category': function ()　{
		return Category.find();
	},
	'topics': function () {
		return Topics.find({});
	},
	'user': function () {
		var data = Meteor.users.findOne(this.userId)
		return data;
	},
	'equalid': function (id) {
		return id == Meteor.userId() ? "panel callout": "panel";
	},
	'next_page': function () {
		var page = Session.get('page') -0 + 1;
		// console.log(Session.get('page'));
		// console.log(page);
		// 
		return "/go/p" + page;
	},
	'prev_page': function ()　{
		var page = Session.get('page') - 1;
		return "/go/p" + page;
	},
	'page_count': function () {

	},
	'active': function (name) {
		if($.trim(this.name) == "" && Session.get("category") == null) {
			return "active";
		}
		return Session.equals("category", this.name ) ? "active": "";
	}
	// 'fromnow': function (t) {
	// 	return moment.utc(t).fromNow();
	// }
	// use tpl {{equalid userId}}
});
Template.topic.helpers({
	'topic': function () {
		var topic_id = Session.get('topic_id');
		Topics.update({_id:topic_id},{$inc:{views:1}});
		return Topics.findOne({_id:topic_id});
	}
	// 'fromnow': function (t) {
	// 	return moment.utc(t).fromNow();
	// },
	
});
Template.replys.helpers({
	'replys': function() {
		var topic_id = Session.get('topic_id');
		return Replys.find({Topic_id: topic_id});
	}
})
Template.topic.events({
	'submit form': function (evt) {
		evt.preventDefault();

		var data = formData(evt.currentTarget);
		// console.log(data);
		data.userId = Meteor.userId();
		data.Topic_id = Session.get('topic_id');
		data.created = new Date();
		Replys.insert(data, function (err, result) {
			if(err) {
				return console.log(err);
			} else if (result) {
				Topics.update({_id: data.Topic_id}, {$inc: {reply_count: 1}});
			}
		});
		$('.reply').val('');
		// console.log(data);

	}
});
Template.topics.events({
	'click .close': function (evt) {
		$(evt.currentTarget).parent('.alert-box');
		Session.set('errbox', false);
	},
	'click .showerr': function () {
		Session.set('errbox', true);
	}
	// 'click .clearsession': function () {
	// 	_.each(['title', 'content'], function(post) {
	// 		Session.set(post, '');
	// 	});
	// }
});
Template.new.category = function () {
	return Category.find();
}
Template.new.events({
	'submit form': function (evt) {
		evt.preventDefault();
		// _.each(formData(evt.currentTarget), function(field) {
		// 	Session.set(field.name, field.value);
		// });
		var data = formData(evt.currentTarget);
		if($.trim(data.title) == '') {
			return showErr("标题不能为空");
		}
		data.userId = Meteor.userId();
		data.created = new Date();
		data.updated = new Date();
		data.reply_count = 0;
		data.views = 0;
		console.log(data);
		Topics.insert(data, function(err, result) {
			if(err) {
				console.log(err);
				return showErr(err);
			}
		});
		Meteor.Router.to('/p');
	}
});
Template.member.helpers({	
	'member': function() {
		return Meteor.users.findOne({_id: Session.get('uid')});
	},
	'topics': function() {
		return Topics.find({userId: this._id}, {sort: {updated: -1}, limit: 10});
	},
	'replys': function () {
		return Replys.find({userId: this._id}, {sort: {created: -1}, limit: 10})
	},
	'reply_to': function (topic_id) {
		return Topics.findOne({_id: topic_id},{fields: {title:1}});
	}
})
Accounts.ui.config({
	passwordSignupFields:'USERNAME_AND_OPTIONAL_EMAIL'
	// passwordSignupFields: 'USERNAME_AND_OPTIONAL_EMAIL'
});

Meteor.Router.add({
	"/": function () {
		Session.set('category', null);
		return "topics";
	},
	"/p/:page?": function (page) {
		// if (page) {
		// 	Session.set('page', page);
		// 	console.log (Session.get('page'));
		// }
		return "topics";
	},
	"/new": function () {
		return "new"
	},
	"/t/:tid": function (tid) {
		Session.set('topic_id', tid);
		return "topic"
	},
	"/go/p:page": function (page) {
		// if (page) {
		// 	Session.set('page', page);
		// 	console.log (Session.get('page'));
		// }
		Session.set('page', page);
		return "topics";
	},
	"/u/:userId": function (uid) {
		Session.set('uid', uid);
		return "member";
	},
	"/c/:category": function (category) {
		Session.set('page', 1);
		Session.set('category', category);
		return "topics";
	}
});

// Meteor.Router.page();